package nafos.security.filter

import nafos.security.config.SecurityConfig
import nafos.server.BizException
import nafos.server.request.NsRequest
import nafos.server.response.NsResponse
import nafos.server.util.AESUtil
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
import java.net.URLDecoder
import java.net.URLEncoder
import javax.servlet.http.Cookie
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse


internal const val cookieStart = "nafosCookie"

fun NsRequest.nafosCookieId(): String? {
    var value: String? = getHeader(cookieStart)
    if (value.isNullOrBlank()) {
        value = this.cookies?.firstOrNull { it.name == cookieStart }?.value
    }
    if (value.isNullOrBlank()) {
        return null
    }
    return AESUtil.decrypt(URLDecoder.decode(value))
}

inline fun currentNafosCookie(): String {
    val servletRequestAttributes = RequestContextHolder.getRequestAttributes() as ServletRequestAttributes
    val request: NsRequest = servletRequestAttributes.request as NsRequest
    return request.nafosCookieId() ?: throw BizException.LOGIN_SESSION_TIME_OUT
}

fun NsResponse.setNafosCookieId(cookieId: String) {
    val servletRequestAttributes = RequestContextHolder.getRequestAttributes() as ServletRequestAttributes
    val response: HttpServletResponse = servletRequestAttributes.response
    response.addCookie(Cookie(cookieStart, URLEncoder.encode(AESUtil.encrypt(cookieId))))
}

/**
 * 浏览器cookie存放时间
 */
fun NsResponse.setLocalNafosCookieId(cookieId: String, maxAge: Int = SecurityConfig.getSessionTimeOut(), cookiePath: String? = null) {
    val servletRequestAttributes = RequestContextHolder.getRequestAttributes() as ServletRequestAttributes
    val request: HttpServletRequest = servletRequestAttributes.request
    val response: HttpServletResponse = servletRequestAttributes.response
    val cookie = Cookie(cookieStart, URLEncoder.encode(AESUtil.encrypt(cookieId)))
    //设置路径
    cookie.path = cookiePath ?: request.contextPath
    //过期时间、与redis一致
    cookie.maxAge = maxAge
    //不允许浏览器获取
    cookie.isHttpOnly = true
    response.addCookie(cookie)
}